from hashlib import md5
import time
from flask import Blueprint, request, g, current_app
import os
from .forms import UploadImageForm, AddBannerForm, EditBannerForm
from utils import restful
from flask_jwt_extended import jwt_required, get_jwt_identity
from exts import db
from models.auth import UserModel,Permission
from models.post import BannerModel, PostModel, CommentModel, BoardModel
from datetime import datetime, timedelta
from .decoartors import permission_required

bp = Blueprint("cmsapi", __name__, url_prefix="/cmsapi")


@bp.before_request
@jwt_required()
def cmsapi_before_request():
    if request.method == 'OPTIONS':
        return
    identity = get_jwt_identity()
    user = UserModel.query.filter_by(id=identity).first()
    if user:
        setattr(g, "user", user)


@bp.get("/")
@jwt_required()
def mytest():
    # 这个identify是当初通过create_access_token传入的identity
    identity = get_jwt_identity()
    return restful.ok(message="success", data={"identity": identity})


@bp.post('/banner/image/upload')
@permission_required(Permission.BANNER)
def upload_banner_image():
    form = UploadImageForm(request.files)
    if form.validate():
        image = form.image.data
        ext = image.filename.split('.')[-1]
        filename = md5((g.user.email + str(time.time())).encode('utf-8')).hexdigest() + '.' + ext
        image_path = os.path.join(current_app.config['BANNER_IMAGE_SAVE_PATH'], filename)
        image.save(image_path)
        return restful.ok(data={'image_url': filename})
    else:
        message = form.messages[0]
        return restful.params_error(message=message)


# 添加轮播图
@bp.post('/banner/add')
@permission_required(Permission.BANNER)
def add_banner():
    form = AddBannerForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner_model = BannerModel(name=name, image_url=image_url, link_url=link_url, priority=priority)
        db.session.add(banner_model)
        db.session.commit()
        return restful.ok(data=banner_model.to_dict())
    else:
        message = form.messages[0]
        return restful.params_error(message=message)


@bp.get("/banner/list")
@permission_required(Permission.BANNER)
def banner_list():
    banners = BannerModel.query.order_by(BannerModel.create_time.desc()).all()
    banner_dicts = [banner.to_dict() for banner in banners]
    return restful.ok(data=banner_dicts)


# 删除轮播图
@bp.post("/banner/delete")
@permission_required(Permission.BANNER)
def delete_banner():
    banner_id = request.form.get("id")
    if not banner_id:
        return restful.params_error(message="没有传入id! ")
    try:
        banner_model = BannerModel.query.get(banner_id)
    except Exception as e:
        return restful.params_error(message="此轮播图不存在! ")
    db.session.delete(banner_model)
    db.session.commit()
    return restful.ok(message="删除成功! ")


# 编辑轮播图
@bp.post("/banner/edit")
@permission_required(Permission.BANNER)
def edit_banner():
    form = EditBannerForm(request.form)
    if form.validate():
        banner_id = form.id.data
        try:
            banner_model = db.session.get(BannerModel, banner_id)
        except Exception as e:
            return restful.params_error(message="此轮播图不存在! ")
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner_model.name = name
        banner_model.image_url = image_url
        banner_model.link_url = link_url
        banner_model.priority = priority
        db.session.commit()
        return restful.ok(data=banner_model.to_dict())
    else:
        message = form.messages[0]
        return restful.params_error(message=message)


# 帖子管理/列表
@bp.get("post/list")
@permission_required(Permission.POST)
def post_list():
    page = request.args.get("page", 1, type=int)
    pre_page_count = current_app.config['PER_PAGE_COUNT']
    start = (page - 1) * pre_page_count
    end = start + pre_page_count
    query_obj = PostModel.query.order_by(PostModel.create_time.desc())
    total_count = query_obj.count()
    posts = query_obj.slice(start, end).all()
    post_list = [post.to_dict() for post in posts]
    return restful.ok(data={"post_list": post_list, "total_count": total_count, "page": page})


# 删除帖子
@bp.post("/post/delete")
@permission_required(Permission.POST)
def delete_post():
    post_id = request.form.get("id")
    try:
        post_model = db.session.get(PostModel, post_id)
    except Exception as e:
        return restful.params_error(message="此帖子不存在! ")
    db.session.delete(post_model)
    db.session.commit()
    return restful.ok(message="删除成功! ")


# 获取评论列表
@bp.get("/comment/list")
@permission_required(Permission.COMMENT)
def comment_list():
    comments = CommentModel.query.order_by(CommentModel.create_time.desc()).all()
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_list.append(comment_dict)
    return restful.ok(data=comment_list)


# 删除评论
@bp.post("/comment/delete")
@permission_required(Permission.COMMENT)
def delete_comment():
    comment_id = request.form.get("id")
    CommentModel.query.filter_by(id=comment_id).delete()
    return restful.ok()


# 用户列表
@bp.get("/user/list")
@permission_required(Permission.USER)
def user_list():
    users = UserModel.query.order_by(UserModel.join_time.desc()).all()
    user_dict_list = [user.to_dict() for user in users]
    return restful.ok(data=user_dict_list)


@bp.post("/user/active")
@permission_required(Permission.USER)
def user_active():
    # is_active, id
    # 0/1
    is_active = request.form.get("is_active", type=int)
    user_id = request.form.get("id")
    user = UserModel.query.get(user_id)
    user.is_active = bool(is_active)
    db.session.commit()
    return restful.ok(data=user.to_dict())


# 板块帖子数量
@bp.get('/board/post/count')
def board_post_count():
    # 获取板块下的帖子数量
    board_post_count_list = db.session.query(BoardModel.name, db.func.count(BoardModel.name)).join(PostModel).order_by(
        db.func.count(BoardModel.name).desc()).group_by(
        BoardModel.name).all()
    board_names = [i[0] for i in board_post_count_list]
    post_counts = [i[1] for i in board_post_count_list]
    return restful.ok(data={"board_names": board_names, "post_counts": post_counts})


# 七天发布帖子数量
@bp.get("/day7/post/count")
def day7_post_count():
    now = datetime.now()
    seven_dat_ago = now - timedelta(days=7, hours=now.hour, minutes=now.minute, seconds=now.second,
                                    microseconds=now.microsecond)
    day7_post_count_list = db.session.query(db.func.date_format(PostModel.create_time, '%Y-%m-%d'),
                                            db.func.count(PostModel.id)).filter(
        PostModel.create_time >= seven_dat_ago).group_by(db.func.date_format(PostModel.create_time, '%Y-%m-%d')).all()
    # 循环7天内帖子,如果当天没有帖子,则添加0
    day7_post_count_dict = {}
    for i in range(7):
        day = (now - timedelta(days=i, hours=now.hour, minutes=now.minute, seconds=now.second,
                               microseconds=now.microsecond)).strftime("%Y-%m-%d")
        day7_post_count_dict[day] = 0
    for day, count in day7_post_count_list:
        day7_post_count_dict[day] = count
    datas = list(day7_post_count_dict.keys())
    counts = list(day7_post_count_dict.values())
    return restful.ok(data={"datas": datas, "counts": counts})
